import { Base } from "../../utils/base.js";
import { ProductList } from "list-model.js";
import { Product } from '../product/product-model.js';
import { Cart } from '../cart/cart-model.js';
import { Order } from '../order/order-model.js';
var order = new Order();
var product = new Product();
var base = new Base();
var productlist = new ProductList();
var cart = new Cart();

var selectIndex;
var attrIndex;
var num = 20;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputShowed: false,
    inputVal: "",
    btnChange:true,
    hiddenAttrBox: true,
    productCounts: 1,
    allselect: 0, //sku全选中状态，1表示全选中
    loadingHidden: true,
    noMore:false, 
    searchLoading:false,
    page:1,
    moreSort:true,
    saleSort: false,
    priceSort: false,
    sort:'sale,min_price',
    isUp:false,
    show_search : 0,
    searchHistory: [
      { id: 1, name:'办公室'},
      { id: 1, name: '多肉' },
      { id: 1, name: '绿萝' },
      { id: 1, name: '室内' },
      { id: 1, name: '康乃馨' },
    ],
  },
  onLoad: function (options) {
    var id = options.id;
    var show_search = options.search ? options.search : 0;
    this.setData({
      show_search
    })
    var val = options.value;
    this.data.val = val;
    if (id){
      this.data.params = {'cat_id': id, 'num': num,  'child': true, };
    } else if (options.hot){
      this.data.params = { 'num': num, 'hot': 1,};
    }else{
      this.data.params = { 'num': num,};
    }
    if (show_search == 0){
      this._loadData();
    }
    
  },

  /*加载商品数据*/
  _loadData: function () {
    var that = this; 
      productlist.getProductData(this.data.page, this.data.sort,this.data.params,(data) => {
        that.setData({
          productData: data.items,
          pageCount:data._meta.pageCount,
          loadingHidden: true,
        })
        if (data._meta.pageCount == 1) {
          that.setData({
            searchLoading: false,
            noMore: true,
          })
        }
      })
  },

  getMoreSort:function(){
    this.data.sort = 'create_at,sale,min_price';
    this.data.page = 1;
    this.setData({
      moreSort: true,
      saleSort: false,
      priceSort: false,
      noMore: false,
      loadingHidden: false,
    })
    this._loadData();
  },
  getSaleSort: function () {
    // this.data.sort = 'sale';
    if (this.data.isUp == true) {
      this.setData({
        isUp: false
      })
      this.data.sort = '-sale';
    } else if (this.data.isUp == false) {
      this.setData({
        isUp: true
      })
      this.data.sort = 'sale';
    }
    this.data.page = 1;
    this.setData({
      moreSort: false,
      saleSort: true,
      priceSort: false,
      noMore: false,
      loadingHidden: false,

    })
    this._loadData();
  },
  getPriceSort: function () {
    if (this.data.isUp == true) {
      this.setData({
        isUp: false
      })
      this.data.sort = '-min_price';
    } else if (this.data.isUp == false) {
      this.setData({
        isUp: true
      })
      this.data.sort = 'min_price';
    }
    this.data.page = 1;
    this.setData({
      moreSort: false,
      saleSort: false,
      priceSort: true,
      noMore: false,
      loadingHidden: false,
    })
    this._loadData();
  },

  /*搜索*/
  showInput: function () {
    this.setData({
      inputShowed: true,
      show_search: 1
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },
  searchWord:function(e){
    var name = e.currentTarget.dataset.word;
    this.setData({
      inputVal: name
    })
    this.searchBtn(false);
  },
  searchBtn:function(newWord = true){
    if(newWord && this.data.inputVal){
      var item = { id: 1, name:this.data.inputVal}
      this.data.searchHistory.unshift(item);
      var res = this.data.searchHistory
      this.setData({
        searchHistory:res
      })
    }
    this.setData({
      show_search : 0
    })
    var page =1;
    this.data.params = { 'num': num, 'name':this.data.inputVal };
    productlist.getProductData(page,20, this.data.params,(data) => {
      this.setData({
        productData: data.items,
        pageCount: data._meta.pageCount,
        page:page,
        scrollTop:0,
       
      })
      if(page==this.data.pageCount){
        this.setData({
          searchLoading: false,
          noMore: true,
        })
      }
      if (0 == this.data.pageCount) {
        this.setData({
          noMore: false,
        })
      }
    })
  },

  // 改变商品列表列数
  changeBtn: function(){
    this.setData({
      btnChange:!this.data.btnChange
    })
  },

  /*切换商品属性*/
  onTabsItemTap: function (event) {
    var productDetail = this.data.productDetail;
    var data = product.changAttr(event, productDetail);
    this.setData({
      'productDetail.attributes': data
    });
    var skusindex = product.changProductinf(this.data.productDetail);
    if (skusindex != undefined) {
      this.setData({
        'allselect': 1,
        'skus': this.data.productDetail.skus[skusindex],
      });

    } else {
      this.setData({
        'allselect': 0,
      });
    }

  },

  /*调整商品数目*/
  onChangeCountsTap: function (event) {
    var maxCount, selected_skus_id;
    if (this.data.allselect == "0") {
      maxCount = this.data.productDetail.product.stock
    } else if (this.data.allselect == "1") {
      maxCount = this.data.skus.stock;
    }
    var currentNum = product.changeCounts(event, this.data.productCounts);
    if (currentNum > maxCount) {
      currentNum = maxCount;
      if(maxCount == 0){
        currentNum=1;
        wx.showToast({
          title: '暂无库存~',
          icon: 'none',
          duration: 2000
        })
      }else{
        wx.showToast({
          title: '大于库存~',
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      'productCounts': currentNum
    })
  },
  //手动输入商品数目
  countChange: function (e) {
    var currentNum = e.detail.value;
    var maxCount, selected_skus_id;
    if (this.data.allselect == "0") {
      maxCount = this.data.productDetail.product.stock
    } else if (this.data.allselect == "1") {
      maxCount = this.data.skus.stock;
    }
    if (currentNum && currentNum < 1) {
      currentNum = 1;
      wx.showToast({
        title: '数量必须是正整数',
        icon: 'none',
        duration: 2000
      })
    }
    if (currentNum > maxCount) {
      currentNum = maxCount;
      if (maxCount == 0) {
        currentNum = 1;
        wx.showToast({
          title: '暂无库存~',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '大于库存~',
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      'productCounts': currentNum
    })
  },

  //加入购物车或立即购买
  onAddingToCartTap: function (event) {
    var flag = product.getDataSet(event, 'from')
    if (product.isSelectAll(this.data.productDetail).skustr) {
      this.setData({
        'selectLabel': product.isSelectAll(this.data.productDetail).selectLabel
      })
      var params = {
        'sku_id': product.isSelectAll(this.data.productDetail).skustr,
        'num': this.data.productCounts ? this.data.productCounts : 1,
        'prom_type': this.data.prom_type,
        'prom_id': this.data.prom_id,
      }
      if (flag == 'cart') {
        params.type = 0;
      } else {
        params.type = 1;
      }
      cart.addProduct2Cart(params, (data) => {
        var status = data.status,
          msg = data.msg;
        if (status == 1 && flag == 'cart') {
          this.cancelattrbox();
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
          this.setData({
            'productCounts': 1,
          });
        } else if (status == 1 && flag == 'buy') {
          wx.navigateTo({
            url: '../order/order?from=buy' + '&id=' + msg

          })
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000
          })
        }

      });
    } else {
      this.setData({
        unselectLabel: product.isSelectAll(this.data.productDetail).unselectLabel,
        'selectLabel': false
      })
      if (this.data.productDetail.product.stock == 0) {
        wx.showToast({
          title: '暂无库存！',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请选择  ' + product.isSelectAll(this.data.productDetail).unselectLabel,
          icon: 'none',
          duration: 2000
        })
      }
    }

  },
  //商品属性弹出框显示
  showattrbox: function (e) {
    var product_id = productlist.getDataSet(e, 'id');
    this.setData({
      'hiddenAttrBox': !this.data.hiddenAttrBox,
      'productCounts': 1,
      
    });
    product.getSkuData(product_id, (sku) => {
      this.setData({
        'productDetail': sku,
        'allselect': 0
      });
    })
  },
  //商品属性弹出框关闭
  cancelattrbox: function (e) {
    if (product.isSelectAll(this.data.productDetail).unselectLabel) {
      this.setData({
        'hiddenAttrBox': true,
        'unselectLabel': product.isSelectAll(this.data.productDetail).unselectLabel,
      })
    } else {
      this.setData({
        'hiddenAttrBox': true,
      })
    }
  },

//滚动加载
  lower: function (e) {
    var page = parseInt(this.data.page) + 1;
    if(page<=this.data.pageCount){
        this.setData({
          searchLoading: true,
        })
        productlist.getProductData(page,20,this.data.params,(data) => {
          this.scrollLoadData(data, page);
        })
    }else{
      this.setData({
        noMore: true,
      })
    } 
  },

  scrollLoadData:function(data,page){
    var productData = this.data.productData;
    productData = productData.concat(data.items)
    this.setData({
      productData: productData,
      page: page,
    })
    if(page==this.data.pageCount){
      this.setData({
        searchLoading: false,
        noMore:true,
      })
    }
  },
  
  /*跳转到商品详情*/
  onProductsItemTap: function (event) {
    var id = product.getDataSet(event, 'id');
    var skuid = product.getDataSet(event, 'skuid');
    var uid = wx.getStorageSync('uid');
    if(skuid){
      wx.navigateTo({
        url: '../product/product?id=' + id + '&skuid=' + skuid
      })
    }else{
      wx.navigateTo({
        url: '../product/product?id=' + id 
      })
    }
  },

  //加入直接购买
  buynow: function (event) {
    var sku_id = product.isSelectAll(this.data.productDetail).skustr && product.isSelectAll(this.data.productDetail).skustr;
    if (sku_id) {
      this.setData({
        'selectLabel': product.isSelectAll(this.data.productDetail).selectLabel
      })
      var params = {
        sku_id: sku_id,
        num: this.data.productCounts,
        prom_type: 0,
        prom_id: 0
      }
      order.getbuy(params, (data) => {
        if (data.status == 1) {
          wx.navigateTo({
            url: '../order/order?sku_id=' + sku_id + '&num='
              + this.data.productCounts + '&prom_type=0&prom_id= 0 &from=' + 'buy'

          })
        }
      })
    } else {
      this.setData({
        unselectLabel: product.isSelectAll(this.data.productDetail).unselectLabel,
        'selectLabel': false
      })
      if (this.data.productDetail.product.stock == 0) {
        wx.showToast({
          title: '暂无库存！',
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: '请选择  ' + product.isSelectAll(this.data.productDetail).unselectLabel,
          icon: 'none',
          duration: 2000
        })
      }
    }

  },
})